home *** CD-ROM | disk | FTP | other *** search
/ The Very Best of Atari Inside / The Very Best of Atari Inside 1.iso / mint / mntlb20 / lib / fwrite.c < prev    next >
C/C++ Source or Header  |  1992-03-10  |  1KB  |  67 lines

  1. /* from Dale Schumacher's dLibs */
  2.  
  3. #include <stddef.h>
  4. #include <stdio.h>
  5. #include <limits.h>
  6. #include <assert.h>
  7. #include <string.h>
  8. #include "lib.h"
  9.  
  10. size_t  fwrite(data, size, count, fp)
  11.     const register void *data;
  12.     size_t size;
  13.     size_t count;
  14.     register FILE *fp;
  15. {
  16.     register size_t n, m;
  17.     register long l = 0;
  18.     long space;
  19.     unsigned int f = fp->_flag;
  20.  
  21.     if(f & _IORW) {
  22.         fp->_flag |= _IOWRT;
  23.         f = (fp->_flag &= ~(_IOREAD | _IOEOF));
  24.     }
  25.  
  26.     if(!(f & _IOWRT)            /* not opened for write? */
  27.         || (f & (_IOERR | _IOEOF)))        /* error/eof conditions? */
  28.         return(0);
  29.  
  30.     assert ((data != NULL));
  31.     assert ((size != 0));
  32.     n =  count * size;
  33.     assert ( n <= (size_t)LONG_MAX);  /* otherwise impl will not work */
  34.  
  35.     space = fp->_bsiz - fp->_cnt;
  36.     while(n > 0)
  37.     {
  38.         m = (n > space)? space: n;
  39.         bcopy(data, fp->_ptr, m);
  40.         fp->_ptr += m;
  41.         fp->_cnt += m;
  42.         space -= m;
  43.         if(space == 0)
  44.         {
  45.         if(fflush(fp))
  46.             return 0;
  47.         space = fp->_bsiz;
  48.         if(f & _IORW)
  49.             fp->_flag |= _IOWRT; /* fflush resets this */
  50.         }
  51.         l += m;
  52.         data = (char *) data + m;
  53.         n -= m;
  54.         if(n < space)
  55.         continue;
  56.         if((m = _write(fp->_file, data, (long)n)) != (long)n)
  57.         {
  58.         fp->_flag |= _IOERR;
  59.         return 0;
  60.         }
  61.         l += m;
  62.         break;
  63.     }
  64.     
  65.     return((l > 0) ? ((size_t)l / size) : 0);
  66. }
  67.